package com.liangtian.mdm.material.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.dm.jsp.common.ExcelUtil;
import com.liangtian.mdm.material.common.util.ExcelExportUtil;
import com.liangtian.mdm.material.dao.WlwlDao;
import com.liangtian.mdm.material.model.Wlwl;
import com.liangtian.mdm.material.model.WlwlField;
import com.liangtian.mdm.material.model.WlwlLan;
import com.liangtian.mdm.material.service.WlwlDisService;
import com.liangtian.mdm.material.service.WlwlService;
import com.liangtian.mdm.system.user.dao.SysUserDao;
import com.liangtian.mdm.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

@Service
public class WlwlServiceImpl implements WlwlService {

    private static Logger log = LoggerFactory.getLogger(WlwlServiceImpl.class.getName());

    // 注入物料dao接口
    @Autowired
    private WlwlDao wlwlDao;
    @Autowired
    private WlwlDisService wlwlDisService;
    @Autowired
    SysUserDao sysUserDao;

    @Override
    @SuppressWarnings({"rawtypes", "unchecked"})
    public PageInfo queryWlwl(Map<String, Object> cond) {
        PageInfo<List<Wlwl>> pageInfo = null;
        try {
            /*
             * 参数
             * @params参数详情 pageNum 总页数
             * @params参数详情 length 每页显示条数
             * @params参数详情 start 起始条数
             * @params参数详情 draw 请求次数
             * @return 分页条件下的
             */
            Object pNo = cond.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(cond.get("limit").toString());// 模型定义页面要显示数据条数
            // 例如
            // 10,20,50,100
            //--edit by wangyk at 180521:物料代码查询-特征值搜索专用，前台传过来的field为tzlzSearchCond，具体值参见下面的注释。
            //cond.put("tzlzSearchCond","品牌@@@@小米;;;;屏幕大小@@@@5.'0");
            if (!StringUtils.isEmpty((String) cond.get("tzlzSearchCond"))) {
                String tzlzSearchSql = setTzlzSearchCond(cond);
                cond.put("tzlzSearchSql", tzlzSearchSql);
            }

            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<Wlwl> wlwl_lst = wlwlDao.getWlwlByCond(cond);
            pageInfo = new PageInfo(wlwl_lst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    private String setTzlzSearchCond(Map<String, Object> cond) {
        String tzlzSearchCond = (String) cond.get("tzlzSearchCond");
        String[] tzlSearchArr = tzlzSearchCond.split(";;;;", -1);
        StringBuffer sb = new StringBuffer();

        //TODO:bug，单引号
        for (String tzlSearchStr : tzlSearchArr) {
            String[] tzlCond = tzlSearchStr.split("@@@@", -1);
            String tzlStr = tzlCond[0];
            String tzlzStr = tzlCond[1];
            //--对单引号特殊处理，否则sql会报异常
            if (tzlzStr.contains("'")) {
                tzlzStr = tzlzStr.replaceAll("'", "''");
            }
            sb.append(" and exists(select 1 from wl_wl_tzl tt where t.wlbm=tt.wlbm " +
                    " and tt.tzlmc='" + tzlStr + "' and tt.tzlz='" + tzlzStr + "')");
        }
        return sb.toString();
    }

    @Override
    public Wlwl getWlwlByWlbm(String wlbm) {
        if (StringUtils.isNotEmpty(wlbm)) {
            return wlwlDao.getWlwlByWlbm(wlbm);
        } else {
            return null;
        }
    }

    @Override
    public List<Wlwl> getWlwlByWllbid(String wllbid) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<String> getQcSimilar(Map<String, Object> cond) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void updateWlwl(Wlwl wlwl) {
        // TODO Auto-generated method stub

    }

    @Override
    public void updateWlwlFiled(Map<String, Object> cond) {
        wlwlDao.updateWlwlFiled(cond);
    }

    @Override
    public int updateStatus(List<String> ids, String status) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void updateWlwlStatus(Map<String, Object> cond) {
        wlwlDao.updateWlwlStatus(cond);

    }

    @Override
    public PageInfo<Wlwl> selectWlwl(Map<String, Object> cond) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void wlwlExport(Map<String, Object> cond,
                           HttpServletResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void gdWlwl(Map<String, Object> cond, List<String> list) {
        wlwlDao.insertWlwlGdByCond(cond);
        wlwlDao.deleteWlwlByIdS(list);
    }

    @Override
    public List<WlwlLan> getWlwlLan(Map<String, Object> cond) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void wlwlMxExport(Map<String, Object> cond,
                             HttpServletResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void insertWlwlDis(List<String> ids, String actiontype) {
        for (int i = 0; i < ids.size(); i++) {
            Wlwl wlwl = wlwlDao.getWlwlByWlbm(ids.get(i));
            if (wlwl != null) {
                wlwlDisService.insertWlwlDis(wlwl, actiontype);
            }
        }

    }

    @Override
    public PageInfo<Wlwl> queryWlwl_en(Map<String, Object> cond) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<String> getQcSimilar_en(Map<String, Object> cond) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void wlwlExport_en(Map<String, Object> cond,
                              HttpServletResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void handDis(List<String> wlbms, List<String> sysCodes) {
        // TODO Auto-generated method stub

    }

    @Override
    public List<Wlwl> queryWlwlByCond(Map<String, Object> cond) {
        return wlwlDao.getWlwlByCond(cond);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public PageInfo queryWlwlByApprove(Map<String, Object> cond) {
        PageInfo pageInfo = null;
        try {

            /* 参数
             *
             * @params参数详情 pageNum 总页数
             *
             * @params参数详情 length 每页显示条数
             *
             * @params参数详情 start 起始条数
             *
             * @params参数详情 draw 请求次数
             *
             * @return 分页条件下的
             */
            Object pNo = cond.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(cond.get("limit").toString());// 模型定义页面要显示数据条数
            // 例如
            // 10,20,50,100
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<Wlwl> wlWl_lst = wlwlDao.queryWlwlByApprove(cond);
            for (Wlwl wlDr : wlWl_lst) {
                String name = sysUserDao.selectUserByIds(wlDr.getApprove_user()).get(0).getUserName();
                wlDr.setApprove_user(name);
            }
            pageInfo = new PageInfo(wlWl_lst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    @Override
    public void exportWlwl(List<Wlwl> list, List<WlwlField> field, HttpServletResponse response) {
        try {
            String tablename = "物料代码";
            // 声明一个工作薄
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("物料代码");
            XSSFRow row = sheet.createRow(0);
            XSSFCell cell = null;
            CellStyle style = ExcelUtil.createCellTextStyle(workbook);
            cell = row.createCell(0);
            sheet.setDefaultColumnStyle(0, style);
            cell.setCellValue("物料代码");
            cell = row.createCell(1);
            sheet.setDefaultColumnStyle(1, style);
            cell.setCellValue("状态");
            cell = row.createCell(2);
            sheet.setDefaultColumnStyle(2, style);
            cell.setCellValue("长描述(生成)");
            cell = row.createCell(3);
            sheet.setDefaultColumnStyle(3, style);
            cell.setCellValue("短描述(生成)");
            cell = row.createCell(4);
            sheet.setDefaultColumnStyle(4, style);
            cell.setCellValue("类别代码");
            cell = row.createCell(5);
            sheet.setDefaultColumnStyle(5, style);
            cell.setCellValue("类别名称");
            cell = row.createCell(6);
            sheet.setDefaultColumnStyle(6, style);
            cell.setCellValue("计量单位");
            cell = row.createCell(7);
            sheet.setDefaultColumnStyle(7, style);
            cell.setCellValue("备注");
            cell = row.createCell(8);
            sheet.setDefaultColumnStyle(8, style);
            cell.setCellValue("创建人");
            cell = row.createCell(9);
            sheet.setDefaultColumnStyle(9, style);
            cell.setCellValue("发布时间");
            if (field.size() > 0 && field != null) {
                for (int i = 0; i < field.size(); i++) {
                    cell = row.createCell(10 + i);
                    sheet.setDefaultColumnStyle(10 + i, style);
                    cell.setCellValue("" + field.get(i).getFieldName() + "");
                }
            }

            for (int i = 0; i < list.size(); i++) {
                Wlwl getWlLb = list.get(i);
                row = sheet.createRow(i + 1);
                cell = row.createCell(0);
                cell.setCellValue(getWlLb.getWlbm());
                cell = row.createCell(1);
                cell.setCellValue(getWlLb.getStatus().equals("1") ? "活动" : "冻结");
                cell = row.createCell(2);
                cell.setCellValue(getWlLb.getQc());
                cell = row.createCell(3);
                cell.setCellValue(getWlLb.getJc());
                cell = row.createCell(4);
                cell.setCellValue(getWlLb.getLbbm());
                cell = row.createCell(5);
                cell.setCellValue(getWlLb.getLbmc());
                cell = row.createCell(6);
                cell.setCellValue(getWlLb.getJldw());
                cell = row.createCell(7);
                cell.setCellValue(getWlLb.getRemark());
                cell = row.createCell(8);
                cell.setCellValue(getWlLb.getCreatorName());
                cell = row.createCell(9);
                cell.setCellValue(getWlLb.getCreateTime());
                if (field.size() > 0 && field != null) {
                    Class<?> cls = getWlLb.getClass();
                    Method[] methods = cls.getDeclaredMethods();
                    Field[] fields = cls.getDeclaredFields();
                    //通过反射遍历属性字段和值
                    for (int j = 0; j < field.size(); j++) {
                        cell = row.createCell(10 + j);
                        String fieldGetName = StringUtil.parGetName(field.get(j).getField());
                        Method fieldGetMet = cls.getMethod(fieldGetName, new Class[]{});
                        Object fieldVal = fieldGetMet.invoke(getWlLb, new Object[]{});
                        String result = String.valueOf(fieldVal).equals("null") ? "" : String.valueOf(fieldVal);
                        cell.setCellValue(result);
                    }
                }
            }
            ExcelExportUtil.outExportExcel(tablename, workbook, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    @SuppressWarnings({"rawtypes", "unchecked"})
    public PageInfo queryWlwl2(Map<String, Object> cond) {
        PageInfo<List<Wlwl>> pageInfo = null;
        try {
            /*
             * 参数
             * @params参数详情 pageNum 总页数
             * @params参数详情 length 每页显示条数
             * @params参数详情 start 起始条数
             * @params参数详情 draw 请求次数
             * @return 分页条件下的
             */
            Object pNo = cond.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(cond.get("limit").toString());// 模型定义页面要显示数据条数
            // 例如
            // 10,20,50,100
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<Wlwl> wlwl_lst = wlwlDao.getWlwlByCond(cond);
            pageInfo = new PageInfo(wlwl_lst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    @Override
    public PageInfo queryWlwlUpdByApprove(Map<String, Object> cond) {
        PageInfo pageInfo = null;
        try {

            /* 参数
             *
             * @params参数详情 pageNum 总页数
             *
             * @params参数详情 length 每页显示条数
             *
             * @params参数详情 start 起始条数
             *
             * @params参数详情 draw 请求次数
             *
             * @return 分页条件下的
             */
            Object pNo = cond.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(cond.get("limit").toString());// 模型定义页面要显示数据条数
            // 例如
            // 10,20,50,100
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）

            List<Wlwl> wlWl_lst = wlwlDao.queryWlwlUpdByApprove(cond);
            for (Wlwl wlDr : wlWl_lst) {
                String name = sysUserDao.selectUserByIds(wlDr.getApprove_user()).get(0).getUserName();
                wlDr.setApprove_user(name);
            }
            pageInfo = new PageInfo(wlWl_lst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

}
